/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.coupon.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.common.core.constant.CacheConstants;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.DistributionTypeEnum;
import com.ykht.proj.coupon.entity.*;
import com.ykht.proj.coupon.service.*;
import com.ykht.proj.coupon.vo.FxConfRewardVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;


/**
 * 转发记录表
 *
 * @author proj code generator
 * @date 2021-02-01 19:00:17
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/fxforward")
@Api(value = "fxforward", tags = "转发记录表管理")
public class FxForwardController {

	private final FxForwardService fxForwardService;

	private final FxCmsInfoService fxCmsInfoService;

	private final FxConfRewardService fxConfRewardService;

	private final FxWaiterExtService fxWaiterExtService;

	private final FxRewardService fxRewardService;

	private final CnUserExtService cnUserExtService;

	private final FxConfRewardBaseGlobelService fxConfRewardBaseGlobelService;

	private final FxConfRewardBaseService fxConfRewardBaseService;
	/**
	 * 缓存Api
	 */
	private final RedisTemplate redisTemplate;

	/**
	 * 分页查询
	 *
	 * @param page      分页对象
	 * @param fxForward 转发记录表
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('coupon_fxforward_view')")
	public R getFxForwardPage(Page page, FxForward fxForward) {
		return R.ok(fxForwardService.page(page, Wrappers.query(fxForward)));
	}


	/**
	 * 通过id查询转发记录表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('coupon_fxforward_view')")
	public R getById(@PathVariable("id") Long id) {
		return R.ok(fxForwardService.getById(id));
	}

	/**
	 * 新增转发记录表
	 *
	 * @param fxForward 转发记录表
	 * @return R
	 */
	@ApiOperation(value = "新增转发记录表", notes = "新增转发记录表")
	@SysLog("新增转发记录表")
	@PostMapping("/addForward")
//    @PreAuthorize("@pms.hasPermission('coupon_fxforward_add')" )
	public R save(@RequestBody FxForward fxForward) {
		fxForward.setTaskType(1);
		fxForward.setForwardType(3);
		log.info("->开始记录转发{}", fxForward);
		try {
			BigDecimal money = BigDecimal.valueOf(0); //设定佣金
			//根据登录人获取服务员id
			FxWaiterExt waiterExt = fxWaiterExtService.getOne(Wrappers.lambdaQuery(FxWaiterExt.class)
					.eq(FxWaiterExt::getLoginId, SecurityUtils.getUserId())
					.eq(FxWaiterExt::getWorkState, 1));
			log.info("->服务员身份{}", waiterExt);

			fxForward.setCreateUser(SecurityUtils.getUserId());
			fxForward.setCreateTime(LocalDateTime.now());
			fxForward.setWaiterId(waiterExt.getId());
			//如果平台分销总开关关了、不给钱
			FxConfRewardBaseGlobel fxConfRewardBaseGlobel = fxConfRewardBaseGlobelService.getOne(Wrappers.lambdaQuery(FxConfRewardBaseGlobel.class)
					.eq(FxConfRewardBaseGlobel::getDelFlag, 0)
					.eq(FxConfRewardBaseGlobel::getSwitchs, 0)
					.eq(FxConfRewardBaseGlobel::getForwardArticle, 0));
			System.out.println(fxConfRewardBaseGlobel);
			//如果品牌的分销开关关了、不给钱
			FxConfRewardBase fxConfRewardBase = fxConfRewardBaseService.getOne(Wrappers.lambdaQuery(FxConfRewardBase.class)
					.eq(FxConfRewardBase::getBrandId, waiterExt.getBrandId())
					.eq(FxConfRewardBase::getDelFlag, 0)
					.eq(FxConfRewardBase::getSwitchs, 0));
			/*获取登录人门店以及品牌id*/
			/*根据登录人去获取对应门店的转发配置佣金*/
			/*创建奖励记录对象*/
			FxReward fxReward = new FxReward();
			fxReward.setBrandId(waiterExt.getBrandId());
			fxReward.setShopId(waiterExt.getShopId());
			fxReward.setWaiterId(waiterExt.getId());
			fxReward.setCreateUser(SecurityUtils.getUserId());
			fxReward.setCreateTime(LocalDateTime.now());
			fxReward.setCompanyId(waiterExt.getCompanyId());
			fxReward.setType(fxForward.getTaskType());
			fxReward.setTatId(fxForward.getId());
			FxConfRewardVO confReward = new FxConfRewardVO();
			if (fxConfRewardBaseGlobel != null) {
				log.info("->平台最低配置已开启{}", fxConfRewardBaseGlobel);
				if (fxConfRewardBase != null) {
					log.info("->品牌分销配置已开启{}", fxConfRewardBase);
					confReward = fxConfRewardService.findConfByBrandIdAndShopId(waiterExt, DistributionTypeEnum.DISTRIBUTION_TYPE_1.getValue());
					if (confReward != null) {
						log.info("->门店已有配置{}", confReward);
						int i = fxConfRewardBaseGlobel.getForwardArticleMoney().compareTo(confReward.getBaseMoney());
						if (i > 0) {
							fxReward.setMoney(fxConfRewardBaseGlobel.getForwardArticleMoney());
							fxForward.setForwardMoney(fxConfRewardBaseGlobel.getForwardArticleMoney());
						} else {
							fxReward.setMoney(confReward.getBaseMoney());
							fxForward.setForwardMoney(confReward.getBaseMoney());
						}
					} else {
						log.info("已选择使用平台最低配置");
						fxConfRewardBaseGlobel = fxConfRewardBaseGlobelService.queryValue();
						if (fxConfRewardBaseGlobel != null) {
							fxReward.setMoney(fxConfRewardBaseGlobel.getForwardArticleMoney());
							fxForward.setForwardMoney(fxConfRewardBaseGlobel.getForwardArticleMoney());
						}
					}
				}
				//选择平台基本配置
				else {
					log.info("品牌分销配置开关未开启 不记录金额");
					fxForward.setForwardMoney(money);
					fxReward.setMoney(money);
				}
			} else {
				log.info("分销配置未开启 不记录金额");
				fxForward.setForwardMoney(money);
				fxReward.setMoney(money);
			}
			//保存一条转发记录
			fxForwardService.save(fxForward);
			log.info("->保存一条转发记录{}", fxForward);
			fxReward.setTatId(fxForward.getId());
			//保存一条奖励记录
			fxRewardService.insert(fxReward);
			log.info("->保存一条奖励记录{}", fxReward);
			if (fxReward.getMoney().compareTo(BigDecimal.ZERO) == 1) {
				redisTemplate.opsForValue().set(CacheConstants.SOUND_REMIND + waiterExt.getId(), fxReward.getMoney());
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
		return R.ok();
	}

	/**
	 * 修改转发记录表
	 *
	 * @param fxForward 转发记录表
	 * @return R
	 */
	@ApiOperation(value = "修改转发记录表", notes = "修改转发记录表")
	@SysLog("修改转发记录表")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('coupon_fxforward_edit')")
	public R updateById(@RequestBody FxForward fxForward) {
		return R.ok(fxForwardService.updateById(fxForward));
	}

	/**
	 * 通过id删除转发记录表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除转发记录表", notes = "通过id删除转发记录表")
	@SysLog("通过id删除转发记录表")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('coupon_fxforward_del')")
	public R removeById(@PathVariable Long id) {
		return R.ok(fxForwardService.removeById(id));
	}

}
